package com.yuqingsong.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexUtil {
	
	/**
	 * 使用正则表达式查找匹配的字符串，并使用callback.matcher返回的内容替换匹配的字符串。
	 * @param <T>
	 * @param input
	 * @param regex
	 * @param cb
	 * @return 返回替换后的字符串
	 */
	static public String replace(String input,String regex,Callback<String> cb){
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(input);
		StringBuilder sb = new StringBuilder();
		//前一次替换的结束位置
		int prevIndex = 0;		
		while(matcher.find()){
			int start = matcher.start();
			int end = matcher.end();
			sb.append(input.substring(prevIndex,start));
			String matche = input.substring(start,end);
			sb.append(cb.callback(matche));
			prevIndex = end;
		}
		if(prevIndex!=input.length()){
			sb.append(input.substring(prevIndex));
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		String result = replace("abcdbce", "bc", new Callback<String>(){
			public String callback(String param) {
				return "xx";
			}
		});
		System.out.println(result);
	}

}
